package com.bluesimon.wbf.usercenter;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.ume.school.modules.model.ErrorTag;
import org.ume.school.modules.model.entity.UserInviteReward;
import org.ume.school.modules.model.enums.MoneyLogType;
import org.ume.school.modules.model.enums.UserInviteRewardStatus;
import org.ume.school.modules.user.invite.reward.UserInviteRewardService;
import org.ume.school.modules.user.money.UserMoneyService;

import com.bluesimon.wbf.AdminLogined;
import com.bluesimon.wbf.IUser;
import com.bluesimon.wbf.Response;
import com.bluesimon.wbf.usercenter.entity.User;
import com.bluesimon.wbf.usercenter.entity.UserModifyPassword;
import com.bluesimon.wbf.usercenter.enums.UserCheckStatusEnum;
import com.bluesimon.wbf.usercenter.enums.UserStatusEnum;
import com.bluesimon.wbf.usercenter.enums.UserTypeEnum;
import com.bluesimon.wbf.utils.AuthValidate;
import com.bluesimon.wbf.utils.MD5Util;

/**
 * Created by Zz on 2018/8/27.
 */
@RestController
@RequestMapping("/v0.1/admin")
public class AdminCenterController {

    @Resource
    private UserService userService;
    @Resource
    private UserMoneyService userMoneyService;
    @Resource
    private UserInviteRewardService userInviteRewardService;
    

    /**
     * 添加管理员
     *
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Response<User> register(@RequestParam("username") String username,
            @RequestParam("password") String password, HttpServletRequest request, RedirectAttributes attr) {
        Response<User> resp = new Response<>();
        User userDb = userService.getUserByName(username);
        if (userDb != null) {
            resp.setResultCode(ErrorTag.REPEAT_USER_NAME.getCode());
            resp.setResultMsg(ErrorTag.REPEAT_USER_NAME.getMessage());
        }
        else {
            User user = new User();
            user.setUserName(username);
            user.setPassword(MD5Util.getMD5(password));
            user.setNickName(username);
            user.setLastModified(new Date());
            user.setType(UserTypeEnum.ADMIN.getValue());
            user.setStatus(UserStatusEnum.NORMAL.getValue());
            User u = userService.register(user);
            resp.setRows(u);
        }
        return resp;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Response<User> login(@RequestParam("username") String username, @RequestParam("password") String password,
            HttpServletRequest request, RedirectAttributes attr) {
        Response<User> resp = new Response<>();
        User u = userService.login(username, MD5Util.getMD5(password));
        if (u == null) {
            resp.setResultCode(ErrorTag.LOGIN_FAILURE.getCode());
            resp.setResultMsg(ErrorTag.LOGIN_FAILURE.getMessage());
        }
        else if (u.getType() != UserTypeEnum.ADMIN.getValue()) {
            resp.setResultCode(ErrorTag.NOT_ADMIN.getCode());
            resp.setResultMsg(ErrorTag.NOT_ADMIN.getMessage());
        }
        else {
            request.getSession().setAttribute(IUser.LOGIN_ADMIN_USER, u);
            resp.setRows(u);
        }
        return resp;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Response<User> logout(@AdminLogined IUser user, HttpServletRequest request) {
        Response<User> check = AuthValidate.checkAdmin(user);
        if (check != null) {
            return check;
        }
        request.getSession().removeAttribute(IUser.LOGIN_ADMIN_USER);
        Response<User> result = new Response<User>();
        return result;
    }

    /**
     * 获取当前管理员信息
     * @param user
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public Response<User> getUserInfo(@AdminLogined IUser user) {
        Response<User> check = AuthValidate.checkAdmin(user);
        if (check != null) {
            return check;
        }
        User u = userService.getUser(user.getId());
        return new Response<>(u);
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public Response<User> getUser(@PathVariable("id") String id, @AdminLogined IUser user) {
        Response<User> check = AuthValidate.checkAdmin(user);
        if (check != null) {
            return check;
        }
        Response<User> resp = new Response<>();
        User u = userService.getUser(id);
        if (u == null) {
            resp.setResultCode(ErrorTag.NOT_FIND_USER.getCode());
            resp.setResultMsg(ErrorTag.NOT_FIND_USER.getMessage());
        }
        else {
            resp.setRows(u);
        }
        return resp;
    }

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public Response<List<User>> getUsers(@RequestParam(value = "username", required = false) String userName,
            @RequestParam(value = "realname", required = false) String realName,
            @RequestParam(value = "nickname", required = false) String nickName,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "checkstatus", required = false) Integer checkstatus,
            @RequestParam(value = "offset", required = true) String offset,
            @RequestParam(value = "limit", required = true) String limit, @AdminLogined IUser user) {
        Response<List<User>> check = AuthValidate.checkAdmin(user);
        if (check != null) {
            return check;
        }
        Response<List<User>> result = new Response<List<User>>();
        final User query = new User();
        query.setUserName(userName);
        query.setRealName(realName);
        query.setNickName(nickName);
        query.setStatus(status);
        query.setCheckStatus(checkstatus);
        query.setType(UserTypeEnum.NOT_ADMIN.getValue());
        Page<User> list = userService.findAll(query, offset, limit);
        result.setTotal(list.getTotalElements());
        result.setRows(list.getContent());
        return result;
    }

    /**
     * 实名认证
     */
    @RequestMapping(value = "/user/check", method = RequestMethod.POST)
    public Response<User> checkUser(@RequestBody User model, @AdminLogined IUser user) {
        Response<User> check = AuthValidate.checkAdmin(user);
        if (check != null) {
            return check;
        }
        Response<User> resp = new Response<>();
        if (StringUtils.isEmpty(model.getId())) {
            resp.setResultCode(ErrorTag.PARAM_NULL.getCode());
            resp.setResultMsg(ErrorTag.PARAM_NULL.getMessage());
        }
        else {
            User modelDb = userService.getUser(model.getId());
            if (modelDb == null) {
                resp.setResultCode(ErrorTag.NOT_FIND_USER.getCode());
                resp.setResultMsg(ErrorTag.NOT_FIND_USER.getMessage());
            }
            else {
                modelDb.setCheckStatus(model.getCheckStatus());
                modelDb.setCheckReason(model.getCheckReason());
                resp.setRows(userService.update(modelDb));
                
                //认证通过
                if(model.getCheckStatus().intValue() == UserCheckStatusEnum.NORMAL.getValue()){
                    //奖励推荐人DG币
                    User u = userService.getUser(modelDb.getId());
                    if(u.getReferrerId()!=null && !u.getReferrerId().isEmpty()){
                        UserInviteReward uir = userInviteRewardService.findByUserIdAndReferrerId(u.getId(), u.getReferrerId());
                        if(uir!=null && uir.getMoney()>0){
                            uir.setStatus(UserInviteRewardStatus.SUCCESS.getValue());
                            userInviteRewardService.submit(uir);
                            //用户奖励5DG
                            userMoneyService.save(u.getReferrerId(), uir.getTypeId(), uir.getMoney(), MoneyLogType.INVITE_REWARD, null);
                        }
                    }                    
                }
            }
        }
        return resp;
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "/password", method = RequestMethod.POST)
    public Response<User> modifyPassword(@RequestBody UserModifyPassword model, @AdminLogined IUser user) {
        Response<User> check = AuthValidate.checkAdmin(user);
        if (check != null) {
            return check;
        }
        Response<User> resp = new Response<>();
        User u = userService.login(user.getUserName(), MD5Util.getMD5(model.getOldPassword()));
        if (u == null) {
            resp.setResultCode(ErrorTag.OLD_PASSWORD_ERROR.getCode());
            resp.setResultMsg(ErrorTag.OLD_PASSWORD_ERROR.getMessage());
        }
        User userDb = userService.getUser(user.getId());
        userDb.setPassword(MD5Util.getMD5(model.getNewPassword()));
        userDb = userService.update(userDb);
        resp.setRows(userDb);
        return resp;
    }

    /**
     * 初始化账号
     *
     * @return
     */
    @RequestMapping(value = "/init", method = RequestMethod.GET)
    public Response<User> initAdmin() {
        User userDb = userService.getUserByName("admin");
        if (userDb == null) {
            User user = new User();
            user.setNickName("超级管理员");
            user.setRealName("超级管理员");
            user.setUserName("admin");
            // 两次MD5，一次是传输前，一次是传输后
            user.setPassword(MD5Util.getMD5("123456"));
            user.setType(UserTypeEnum.ADMIN.getValue());
            user.setStatus(UserStatusEnum.NORMAL.getValue());
            userService.register(user);
            return new Response<>(user);
        }
        return new Response<>(userDb);
    }
}
